import { defineStore } from "pinia";
import avatar from '@assets/image/暂无头像.svg'
import { reactive, ref } from "vue";
import { getStorage } from "@/utils";
import { storageType } from "@/model/enum";
import { User } from '@/model'
import { getLoginStatus, getUserInfo } from '@/api';

const useHeaderStore = defineStore('header', () => {
    // 登陆框的展开状态
    const showLogin = ref<boolean>(false);
    // cookie用来判断用户是否登陆
    const cookie = ref<string>(getStorage(storageType.SESSION, 'cookie') || '');
    const user = reactive<User>(
        getStorage(storageType.SESSION, 'userInfo') || {
            uid: '',
            userName: '点击登陆',
            avatar: avatar
        }
    )
    // 获取用户的信息
    const getInfo = async () => {
        // 用cookie获取用户id
        const res = await getLoginStatus({ cookie: cookie.value })
        const id = res.data.account.id
        user.uid = res.data.account.id
        const userInfo: any = await getUserInfo(id)
        const { profile: { avatarUrl, nickname } } = userInfo
        user.avatar = avatarUrl
        user.userName = nickname
    }

    return { cookie, showLogin, user, getInfo };
})

export default useHeaderStore